package cn.texous.dns.controller;

import cn.texous.dns.configure.OtherProperties;
import cn.texous.dns.util.AliyunSmsUtils;
import cn.texous.dns.util.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/5/27 18:25
 */
@RestController
@RequestMapping("/sms")
public class SendSmsController {

    private static final Logger log = LoggerFactory.getLogger(SendSmsController.class);

    @Autowired
    private OtherProperties otherProperties;

    /***/
    @GetMapping("/send")
    public Map<String, String> sendSms(HttpServletRequest request) {
        Map<String, String> result = new HashMap<>();
        boolean re = false;
        String ip = IpUtils.getIpAddress(request);
        if (otherProperties.getIp().getWhitelist().contains(ip)) {
            String code = request.getParameter("code");
            String mobile = request.getParameter("mobile");
            String isForeign = request.getParameter("isForeign");
            log.info("发送短信验证码：mobile={}, code={}", mobile, code);
            if (code != null && !"".equals(code)
                    && mobile != null && !"".equals(mobile)) {
                result = AliyunSmsUtils.sendMsg(mobile, code, "1".equals(isForeign));
                return result;
            }
        }
        result.put("result", "0");
        result.put("errorMsg", "没有发送短信验证码");
        return result;
    }

    /***/
    @GetMapping("/sendWarnInfoSms")
    public Map<String, String> sendWarnInfoSms(HttpServletRequest request) {
        Map<String, String> result = new HashMap<>();
        boolean re = false;
        String ip = IpUtils.getIpAddress(request);
        if (otherProperties.getIp().getWhitelist().contains(ip)) {
            String mobile = request.getParameter("mobile");
            String system = request.getParameter("system");
            String warnInfo = request.getParameter("warnInfo");
            String time = request.getParameter("time");
            String isForeign = request.getParameter("isForeign");
            log.info("发送短信告警信息：mobile={},system={}, warnInfo={}, time={}",
                    mobile, system, warnInfo, time);
            if (system != null && !"".equals(system) && warnInfo != null && !"".equals(warnInfo)) {
                result = AliyunSmsUtils.sendWarnInfoSms(mobile,
                        system, warnInfo, time, "1".equals(isForeign));
                return result;
            }
        }
        result.put("result", "0");
        result.put("errorMsg", "没有发送短信验证码");
        return result;
    }


}

